<?php

namespace App\Utils;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class HttpUtil
{
    /**
     * 发送POST请求
     * @param string $url
     * @param array $data
     * @param array $headers 自定义请求头
     * @param int $timeOut 超时时间
     * @return array
     * @throws \Exception
     */
    public static function post(string $url, array $data = [], array $headers = [], int $timeOut = 30): array
    {
        try {
            $client = new Client([
                'timeout' => $timeOut,
                'verify' => false
            ]);

            $defaultHeaders = [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ];

            $response = $client->post($url, [
                'json' => $data,
                'headers' => array_merge($defaultHeaders, $headers)
            ]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (GuzzleException $e) {
            throw new \Exception('HTTP请求失败: ' . $e->getMessage());
        }
    }

    /**
     * 发送流式POST请求
     * @param string $url
     * @param array $data
     * @param array $headers
     * @param int $timeOut
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public static function streamPost(string $url, array $data = [], array $headers = [], int $timeOut = 300)
    {
        return response()->stream(function () use ($url, $data, $headers) {
            // 设置响应头
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('X-Accel-Buffering: no');
            header('Connection: keep-alive');

            $ch = curl_init();
            
            $headers = array_map(function ($key, $value) {
                return "$key: $value";
            }, array_keys($headers), $headers);
            $headers[] = 'Content-Type: application/json';

            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_WRITEFUNCTION => function ($curl, $data) {
                    echo $data;
                    if (ob_get_level() > 0) {
                        ob_flush();
                    }
                    flush();
                    return strlen($data);
                },
                CURLOPT_BUFFERSIZE => 128,
                CURLOPT_TIMEOUT => 300,
                CURLOPT_RETURNTRANSFER => false,
                CURLOPT_HEADER => false
            ]);

            // 确保输出缓冲区是打开的
            if (ob_get_level() == 0) {
                ob_start();
            }

            curl_exec($ch);

            if (curl_errno($ch)) {
                $error = curl_error($ch);
                echo "event: error\n";
                echo "data: " . json_encode(['error' => $error]) . "\n\n";die;
            }

            curl_close($ch);
            ob_end_flush();
            exit;
        }, 200, [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',
            'Connection' => 'keep-alive'
        ]);
    }
}